package com.fs.sw.service.impl;

import com.fs.sw.dao.UsersRepository;
import com.fs.sw.pojo.Users;
import com.fs.sw.service.IRolesService;
import com.fs.sw.service.IUserService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.thymeleaf.expression.Strings;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    UsersRepository usersRepository;

    @Autowired
    IRolesService rolesService;

    @Transactional(rollbackFor=RuntimeException.class)
    @Override
    public void addUser(){
        Users u = new Users();
        u.setName("测试1");
        usersRepository.save(u);
        rolesService.addRoles();
    }

    @Override
    @Transactional
    public void testTransactional() {
        Users u = new Users();
        u.setName("Transactional1");
        usersRepository.save(u);
//        System.out.println(1/0);
        this.testTransactional2();

    }

    @Transactional
    public void testTransactional2() {
        Users u = new Users();
        u.setName("Transactional2");
        usersRepository.save(u);
        System.out.println(1/0);

    }

    public List<Users> findByCriteria(Users user){
        List<String> andConditions = Lists.newArrayList();
        Map<String,Object> bindParameters = Maps.newHashMap();
        if(StringUtils.hasLength(user.getName())){
            andConditions.add("u.name = :name");
            bindParameters.put("name",user.getName());
        }
        StringBuffer jpql = new StringBuffer();
        jpql.append("select * from User u");
        Iterator<String> andConditionsIt = andConditions.iterator();
        if(andConditionsIt.hasNext()){
            jpql.append(" where ").append(andConditionsIt.next());
        }
        while (andConditionsIt.hasNext()) {
            jpql.append(" and ").append(andConditionsIt.next());
        }
        return usersRepository.exeQueryCustNameParm(jpql.toString(),bindParameters);
    }
}
